package jmine.tec.utils.reflection.fast;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author takeshi
 */
public class FastConstructorImpl implements FastConstructor {

    private final Constructor<?> ctor;

    /**
     * @param ctor {@link Constructor}
     */
    public FastConstructorImpl(Constructor<?> ctor) {
        super();
        this.ctor = ctor;
    }

    /**
     * {@inheritDoc}
     */
    public Object build(Object... args) throws Exception {
        try {
            return this.ctor.newInstance(args);
        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t instanceof Error) {
                throw (Error) t;
            }
            throw (Exception) t;
        }
    }

    /**
     * {@inheritDoc}
     */
    public int getArity() {
        return this.ctor.getParameterTypes().length;
    }

    /**
     * {@inheritDoc}
     */
    public Class<?>[] getParamTypes() {
        return this.ctor.getParameterTypes();
    }

    /**
     * {@inheritDoc}
     */
    public Class<?> getDeclaringClass() {
        return this.ctor.getDeclaringClass();
    }

    /**
     * {@inheritDoc}
     */
    public Constructor<?> getConstructor() {
        return this.ctor;
    }

}
